package com.sangeng.filter;

import com.sangeng.domain.LoginUser;
import com.sangeng.domain.Menu;
import com.sangeng.domain.User;
import com.sangeng.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
@Component
public class MenuAccessDecisionManager implements AccessDecisionManager {
    @Resource
    private MenuMapper menuMapper;

    /**
     * 读取 MenuFilter 封装的根据 Url 获取的对应权限列表
     * 读取当前登录用户的用户信息
     * 根据当前用户信息获取该用户所拥有的权限列表
     * 匹配权限列表 一个匹配则正常放行 全部无法匹配则抛出权限不足的异常
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        System.out.println("============>>>当前接口权限列表:"+collection);
        System.out.println("============>>>当前用户信息及拥有权限:"+authentication.getPrincipal().toString());
        for (ConfigAttribute configAttribute : collection) {
            // 当前请求需要的权限
            String needRole = configAttribute.getAttribute();
            //为登录权限则正常返回
            if ("ROLE_LOGIN".equals(needRole)) {
                return;
            }
            Object principal = authentication.getPrincipal();
            if (principal instanceof String){
                throw new BadCredentialsException("未登录");
            }
            // 当前用户所具有的权限
            LoginUser loginUser= (LoginUser) principal;
            List<String> roleList = menuMapper.selectPermsByUserId(loginUser.getUser().getId());
            for (String role : roleList) {
                // 包含其中一个权限即可访问
                if (role.equals(needRole)) {
                    return;
                }
            }
        }
        //抛出权限不足的异常交由 AccessDeniedHandlerImpl 捕获
        throw new AccessDeniedException("SimpleGrantedAuthority!!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
